import ImageMonitor from './ImageMonitor'
import imageUrl from '@/assets/images/bucket.png'
import { isMobile } from '@/utils/index'

/**
 * 容器构造函数
 */
export default function Vessel(_this, ctx) {
  this.vesselWidth = 80
  this.vesselHeight = 80
  this.marginLeft = (_this.clientWidth / 2 - this.vesselWidth / 2)
  this.marginTop = (_this.clientHeight - 2 * this.vesselHeight)
  // 绘制容器
  this.initVessel = () => {
    const imageMonitor = new ImageMonitor()
    imageMonitor.loadImage([imageUrl])
    this.player = imageMonitor.createImage(imageUrl)
    // imageMonitor.loadImage([imageUrl], () => {
    ctx.drawImage(this.player, this.marginLeft, this.marginTop, this.vesselWidth, this.vesselHeight)
    // })
  }
  // 设置容器当前位置
  this.setVesselPosition = (event) => {
    let x = ''
    let y = ''
    if (isMobile()) {
      // 移动端
      if (event) {
        // 手指滑动改变位置
        x = event.changedTouches[0].clientX
        y = event.changedTouches[0].clientY
      } else {
        // 默认位置
        x = _this.clientWidth / 2
        y = _this.clientHeight / 2
      }
    } else {
      // PC端
      x = event.offsetX
      y = event.offsetY
    }
    this.marginLeft = x - this.vesselWidth / 2
    this.marginTop = y - this.vesselHeight / 2
    // 禁止滑到屏幕外
    if (this.marginLeft < 0) this.marginLeft = 0
    if (this.marginLeft > _this.clientWidth - this.vesselWidth) this.marginLeft = _this.clientWidth - this.vesselWidth
    this.marginTop = _this.clientHeight - this.vesselHeight - 30
  }
  // 移动容器
  this.operateVessel = () => {
    const stage = _this.$refs.gamePanel
    let move = false
    this.setVesselPosition()
    stage.addEventListener(_this.eventType.start, (event) => {
      this.setVesselPosition(event)
      move = true
    })
    stage.addEventListener(_this.eventType.end, () => {
      move = false
    })
    stage.addEventListener(_this.eventType.move, (event) => {
      event.preventDefault()
      if (move) this.setVesselPosition(event)
    })
  }
  // 素材接触
  this.contactMelt = (materialList) => {
    for (let i = materialList.length - 1; i >=0; i--) {
      const item = materialList[i]
      if (!item) break
      const l1 = this.marginTop + this.vesselHeight / 2 - (item.materialMarginTop + item.materialHeight / 2)
      const l2 = this.marginLeft + this.vesselWidth / 2 - (item.materialMarginLeft + item.materialWidth / 2)
      const l3 = Math.sqrt(l1 * l1 + l2 * l2)
      // 素材与容器碰撞
      if (l3 <= this.vesselHeight / 2 + item.materialHeight / 2) {
        // 清除素材
        materialList[item.materialId] = null
        // 加分
        switch (item.materialType) {    
          case 0:
            _this.score += 2
            break
          case 1:
            _this.score++
            break
        }
      }
    }
  }
}